﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;

namespace WodLib.Tools
{
    /// <summary>
    /// Stores WodObjects on list, serializes and deserializes them.
    /// </summary>
    public class WodObjectDatabase
    {
        private List<WodObject> objectsList;

        /// <summary>
        /// List of WodObjects.
        /// </summary>
        public List<WodObject> ObjectsList 
        {
            get
            {
                return objectsList;
            }
            set
            {
                objectsList = value;
                if (this.ReferenceChanged != null)
                {
                    this.ReferenceChanged(this,
                        new ReferenceChangedEventArgs(value));
                }
            }
        }

        /// <summary>
        /// Serializes list to file.
        /// </summary>
        /// <param name="filePath">Path to file where list should be saved.</param>
        public void SerializeToFile(string filePath)
        {
            BinaryFormatter formatter = new BinaryFormatter();
            FileStream stream = File.Create(filePath);
            formatter.Serialize(stream, ObjectsList);
            stream.Close();
        }

        /// <summary>
        /// Deserializes list from file.
        /// </summary>
        /// <param name="filePath">Path to file from where list shoudl be loaded.</param>
        public void DeserializeFromFile(string filePath)
        {
            BinaryFormatter formatter = new BinaryFormatter();
            FileStream stream = File.OpenRead(filePath);
            ObjectsList = (List<WodObject>)formatter.Deserialize(stream);
            stream.Close();
        }

        /// <summary>
        /// Create new instance of object with empty list.
        /// </summary>
        public WodObjectDatabase()
        {
            ObjectsList = new List<WodObject>(30);
        }

        /// <summary>
        /// Event is rised when ObjectList is set.
        /// </summary>
        public event EventHandler<ReferenceChangedEventArgs> ReferenceChanged;

        public class ReferenceChangedEventArgs : EventArgs
        {
            public List<WodObject> NewObjectsList { get; private set; }

            public ReferenceChangedEventArgs(List<WodObject> newObjectsList)
            {
                NewObjectsList = newObjectsList;
            }
        }

        public void ImportFromFile(string filePath)
        {
            BinaryFormatter formatter = new BinaryFormatter();
            FileStream stream = File.OpenRead(filePath);
            var tmpList = (List<WodObject>)formatter.Deserialize(stream);
            stream.Close();
            ObjectsList.AddRange(tmpList);
        }
    }
}
